const requestUrl = require('../../../config').requestUrl
const EntryList = require('../../../components/EntryList.js');
Page({
  data: {
    schema:[
    ],
    formData:{
    },
    title: '',
    result: '',
    remark: '',
    apiName: '', 
    listData: [],
    loadState: 'loading',
    performanceEntries: [],
  },

  onLoad(options) {
      wx.setNavigationBarTitle({
        title: options.title,
      })
      
      this.setData({
        title: options.title,
        zh:options.zh,
        remark: options.remark,
        webUrl: options.webUrl
      })
      // 记录页面加载开始时间
    this.pageLoadStartTime = Date.now()
    // 检查性能API支持情况
    if (!wx.getPerformance) {
      this.setData({
        supported: false,
        observerStatus: '当前微信版本不支持性能监控API'
      });
      return;
    }

    // 获取性能对象
    this.performance = wx.getPerformance();
    this.startPerformanceMonitoring();
  },
  startPerformanceMonitoring() {
    // 检查性能对象是否可用
    const performance = wx.getPerformance();
    if (!performance) {
      this.setData({ status: '当前环境不支持性能监控' });
      return;
    }

    // 检查createObserver方法是否存在
    if (typeof performance.createObserver !== 'function') {
      this.setData({ status: '基础库版本过低，不支持性能观察者' });
      return;
    }

    // 创建性能观察者
    this.performanceObserver = performance.createObserver((entryList) => {
      const newEntries = entryList.getEntries();
      console.log('新捕获的性能数据:', newEntries);
      
      // 更新页面数据
      this.setData({
        performanceEntries: [...this.data.performanceEntries, ...newEntries],
        status: `已捕获 ${this.data.performanceEntries.length + newEntries.length} 条数据`
      });
    });
  },
  // 数据请求方法
  fetchData(e) {
    // 记录请求开始时间
    const requestStartTime = Date.now() 
    wx.request({
      url: requestUrl,
      data: {
        theme: 'light',
        noncestr: Date.now()
      },
      success: (res) => {
        // 计算请求耗时并上报
        const requestTime = Date.now() - requestStartTime
        this.reportPerformance(
          2001, // 接口请求时间指标ID
          requestTime, // 请求耗时(ms)
          ['会话接口', 'success', res.statusCode], // 维度信息
          e
        )
        
        this.setData({
          listData: res.data,
          loadState: 'success'
        })
      },
      fail: (err) => {
        // 上报失败的请求
        const requestTime = Date.now() - requestStartTime
        this.reportPerformance(
          2001, // 接口请求时间指标ID
          requestTime,
          ['会话接口', 'fail', err.errMsg], // 包含错误信息的维度
          e
        )
        
        this.setData({
          loadState: 'error'
        })
      }
    })
  },
  // 封装性能上报方法
  reportPerformance(id, value, dimensions,e) {
    // 确保在支持的环境中调用
    if (wx.reportPerformance) {
      try {
        wx.reportPerformance(id, value, dimensions)
        this.setData({
          result: `性能上报成功: ID=${id}, 耗时=${value}ms, 维度=${JSON.stringify(dimensions)}`,
          apiName: e.currentTarget.dataset.apiname 
        })
        console.log(`性能上报成功: ID=${id}, 耗时=${value}ms, 维度=${JSON.stringify(dimensions)}`)
      } catch (e) {
        console.error('性能上报失败:', e)
      }
    } else {
      console.log('当前环境不支持wx.reportPerformance')
    }
  },
  getPerformance(e){
    this.setData({
      result: this.performance,
      apiName: e.currentTarget.dataset.apiname 
    })
  },
  preloadAssets(e){
    let that =this;
    wx.preloadAssets({
      data: [
        {
          type: 'image',
          src: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg',
        },
      ],
      success(resp) {
        console.log(resp)
        that.setData({
          result: resp,
          apiName: e.currentTarget.dataset.apiname 
        })
        console.log('preloadAssets success', resp)
      },
      fail(err) {
        that.setData({
          result: err,
          apiName: e.currentTarget.dataset.apiname 
        })
        console.log('preloadAssets fail', err)
      },
    })
  },
  createObserver(e){
    console.log(this.performanceObserver)
    if(this.performanceObserver){
      this.setData({
        result: "创建监听成功",
        apiName: e.currentTarget.dataset.apiname 
      })
    }else{
      this.setData({
        result: "创建监听失败",
        apiName: e.currentTarget.dataset.apiname 
      })
    }   
  },
  getEntries(e){
    const entries = this.performance.getEntries();
    this.setData({
      result: entries,
      apiName: e.currentTarget.dataset.apiname 
    })
  },
  getEntriesByName(e){
    const matchedEntries = this.performance.getEntriesByName("firstPaint", 'render');
    this.setData({
      result: matchedEntries,
      apiName: e.currentTarget.dataset.apiname 
    })
  },
  getEntriesByType(e){
    const matchedEntries = this.performance.getEntriesByType('render');
    this.setData({
      result: matchedEntries,
      apiName: e.currentTarget.dataset.apiname 
    })
  },
  setBufferSize(e){
    const BufferSize = this.performance.setBufferSize(30);
    console.log(this.performance)
    this.setData({
      result: this.performance,
      apiName: e.currentTarget.dataset.apiname 
    })
  },
  performanceEntry(e){
    const navigationEntries = this.performance.getEntriesByType('navigation')
    if (navigationEntries.length > 0) {
      const firstNavEntry = navigationEntries[0]
      console.log('首个导航性能条目:', firstNavEntry)
      this.setData({
        result: firstNavEntry,
        apiName: e.currentTarget.dataset.apiname 
      })
    }
  },
  disconnect(e){
    this.performanceObserver.disconnect();
    this.setData({
      result: "暂停监听路由",
      apiName: e.currentTarget.dataset.apiname 
    })
  },
  observe(e){
    const Observer = this.performance.createObserver((entryList) => {
      const newEntries = entryList.getEntries();
      console.log('新捕获的性能数据:', newEntries);
    });
     // 开始观察指定类型的性能数据
     try {
      Observer.observe({
        entryTypes: ['navigation'],
        buffered: true // 同时获取已经缓存的性能数据
      });
      this.setData({
        result: "开始监听路由",
        apiName: e.currentTarget.dataset.apiname 
      })
    } catch (error) {
      this.setData({ status: `监控启动失败: ${error.message}` });
    }
  },
})